// home 模块仓库 vuex~
import {reqGetCode} from "@/api/index.js";
import {reqUserRegister} from "@/api/index.js";
import {reqUserLogin} from "@/api/index.js";
import {reqUserInfo} from "@/api/index.js";
import {reqLogout} from "@/api/index.js";

const actions = {
  async getCode({commit}, phone) {
    let xml = await reqGetCode(phone);
    
    if(xml.data.code === 200) {
      commit("GETCODE", xml.data.data);
      return "ko";
    }else {
      return Promise.reject(new Error("false"));
    }
  },

  async userRegister({commit}, user) {
    let xml = await reqUserRegister(user);
    if(xml.data.code === 200) {
      return "ok";
    }else {
      return Promise.reject(new Error("false"));
    }
    
  },

  async userLogin({commit}, user) {    
    let xml = await reqUserLogin(user);
    if(xml.data.code === 200) {
      // console.log(xml.data.data.token);

      localStorage.setItem("TOKEN", xml.data.data.token);

      commit("USERLOGIN", xml.data.data.token);
      return "ok";
    }else {
      return Promise.reject(new Error("false"));
    }
    
  },

  async getUserInfo({commit}) {
    let xml = await reqUserInfo();
    if(xml.data.code === 200) {      
      commit("GETUSERINFO", xml.data); 
      return "ok";
    }else {  
      return Promise.reject(new Error("false"));
    }
    
  },

  async userLogout({commit}) {    
    let xml = await reqLogout();
    
    if(xml.data.code === 200) {
      commit("USERLOGOUT");
    }else {
      return Promise.reject(new Error("false"));
    }
  }
};
const mutations = {    
  GETCODE(state, value) {
    state.code = value;
  },
  USERLOGIN(state, value) {
    state.token = value;
  },
  GETUSERINFO(state, value) {
    state.userInfo = value;
  },
  USERLOGOUT(state) {
    state.token = "";
    state.userInfo = "";
    localStorage.removeItem("TOKEN");
  }
};
const state = {
  code: "",
  token: localStorage.getItem("TOKEN"),
  userInfo: null,
};

const getters = {
  getcode(state) {
    return state.code;
  }
};
export default {
  actions,
  mutations,
  state,
  getters,
}
 